package org.ricks.condition1;

import org.ricks.condition1.event.ConditionCompletedEvent;
import org.ricks.ioc.event.EventBus;
import org.ricks.ioc.event.IEvent;

import java.util.function.Consumer;

public abstract class ProgressCondition<E extends IEvent> implements Condition {
    protected final int targetValue;
    protected volatile int currentValue;
    private final Class<E> eventType;
    private final Consumer<ProgressCondition<E>> onDone;
    private volatile boolean isDone = false;

    public ProgressCondition(int targetValue, Class<E> eventType, Consumer<ProgressCondition<E>> onDone) {
        this.targetValue = targetValue;
        this.eventType = eventType;
        this.onDone = onDone;
    }

    @Override
    public void emit(IEvent event) {
        if (!isDone && eventType.isInstance(event)) {
            handleEvent(eventType.cast(event));
            checkCompletion();
        }
    }

    protected abstract void handleEvent(E event);

    private void checkCompletion() {
        if (currentValue >= targetValue && !isDone) {
            isDone = true;
            if (onDone != null) {
                onDone.accept(this);
            }
            System.err.println("任务完成，开始抛出条件完成事件！！");
            EventBus.post(new ConditionCompletedEvent(this));
        }
    }


    @Override
    public boolean isDone() {
        return isDone;
    }
}
